from django.shortcuts import render
# 导入时间日期
from datetime import datetime, date
# 导入JsonResponse
from django.http import JsonResponse
# 导入类
from studentweb.models import StudentImage
# 导入随机数模块
import random
# 导入settings
from django.conf import settings
# 导入os
import os


def index(request):
    return render(request, 'student/student_image.html')


def image2(request):
    return render(request, 'student/student_image2.html')


def upload_image(request):
    """上传图片的后端处理"""
    # 定义返回值的数据结构
    res = {'code': 0, 'error': ""}
    # 接收文件 --> 使用新名字存储
    rec_image = request.FILES.get('file')
    # 获取一个信息的名字【存储的时候使用】
    new_name = (datetime.now().strftime('%Y%m%d%H%M%S')) + '%04d' % (random.randint(1000, 9999))
    # 拼接出要存储文件的绝对路径
    file_path = os.path.join(settings.MEDIA_ROOT, 'stuimage', new_name + os.path.splitext(rec_image.name)[1])
    # 开始写入
    try:
        f = open(file_path, 'wb')
        # 分多次写入
        for i in rec_image.chunks():
            f.write(i)
        f.close()
    except Exception as e:
        res['code'] = 1
        res['error'] = "存储文件时出现异常，具体原因：" + str(e)

    # 写入到数据库
    try:
        # 准备图片的url
        url = settings.MEDIA_URL + 'stuimage/' + new_name + os.path.splitext(rec_image.name)[1]
        StudentImage.objects.create(id=new_name, url=url, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    except Exception as e:
        res['code'] = 2
        res['error'] = "图片信息存储到数据库出现异常，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def list_values(request):
    """获取所有的照片"""
    # 接收传递过来的数据
    q_str = request.POST.get('inputStr', '')
    q_date_start_str = request.POST.get('q_date_start')
    q_date_end_str = request.POST.get('q_date_end')
    # 把字符串转为datetime
    q_date_start = ""
    q_date_end = ""
    if q_date_start_str:
        str_list = q_date_start_str.split('-')
        q_date_start = datetime(year=int(str_list[0]), month=int(str_list[1]), day=int(str_list[2]))
    if q_date_end_str:
        str_list = q_date_end_str.split('-')
        q_date_end = datetime(year=int(str_list[0]), month=int(str_list[1]), day=int(str_list[2]), hour=23, minute=59,
                              second=59)

    # 获取数据
    objs = StudentImage.objects.filter(id__icontains=q_str)
    # 按照时间过滤
    if q_date_start and q_date_end:
        # 既有开始时间，也有结束时间
        objs = objs.filter(create_time__gte=q_date_start, create_time__lte=q_date_end)
    elif q_date_end:
        # 只有结束时间
        objs = objs.filter(create_time__lte=q_date_end)
    elif q_date_start:
        objs = objs.filter(create_time__gte=q_date_start)

    # list --- values
    objs = list(objs.values('id', 'url', 'create_time').order_by('-create_time'))

    # 返回
    return JsonResponse({'code': 0, 'msg': "", 'count': len(objs), 'data': objs, })


def list_images(request):
    # 接收传递的数据
    page = int(request.GET.get('page'))
    limit = int(request.GET.get('limit'))

    # 获取所有的数据
    objs = list(StudentImage.objects.all().values().order_by('-create_time'))

    # 定义一个集合重新整理数据
    objs_data = []
    # 遍历objs
    for index, value in enumerate(objs):
        # 定义一个temp_dict
        temp_dict = {}
        temp_dict['id'] = value.get('id')
        temp_dict['image'] = value.get('url')
        temp_dict['title'] = value.get('title')
        temp_dict['remark'] = value.get('remark')
        temp_dict['time'] = value.get('create_time').strftime("%Y-%m-%d %H:%M:%S")
        # 附加
        objs_data.append(temp_dict)

    # 分页数据
    one_page_data = objs_data[(page - 1) * limit: page * limit]
    # 返回
    return JsonResponse({'code':0, 'count':len(objs_data), 'data': one_page_data})